<?php
class Helper_BSS_CSV
{
	static function exportCsv($data)
	{
		header("Content-type: text/csv;");
		header("Content-Disposition: attachment; filename=" . date("YmdHis") . ".csv");
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Expires: 0');
		header('Pragma: public');
		echo $data;
	}
	
	static function Kh()
	{
		/* load the required classes */
		require_once Q::ini('custom_system/lib_dir')."phpbase/Column.class.php";
		require_once Q::ini('custom_system/lib_dir')."phpbase/Record.class.php";
		require_once Q::ini('custom_system/lib_dir')."phpbase/Table.class.php";
		require_once Q::ini('custom_system/lib_dir')."phpbase/WritableTable.class.php";
		/* 数据表头*/	
		$fields = array(
			array("FID" , DBFFIELD_TYPE_CHAR, 50),
			array("KHNAME" , DBFFIELD_TYPE_CHAR, 50)
		);
		/* create a new table */
		$tableNew = XBaseWritableTable::create(Q::ini('custom_system/base_url')."dbf/KHData.dbf",$fields);
		/* insert some data */
		$customer = Customer::find()->order('c_no desc')->asArray()->getAll();
		foreach ($customer as $c)
		{
			$r =& $tableNew->appendRecord();
			$r->setObjectByName("FID",$c['c_no']);
			$r->setObjectByName("KHNAME",$c['c_name']);
			$tableNew->writeRecord();
		}
		/* close the table */
		$tableNew->close();
	}
	
	//把数据导入系统
	static function fileToData()
	{
		//$_REQUEST
		$filename = $_REQUEST['fileName'];
		$data = $_REQUEST['DATA'];
		$t = $_SESSION['UGType'];
		$userID = $_SESSION['attrID'];
		
	}
	
	static function csvFileToArray($filename)
	{
		$handle = fopen($filename,'r',false);
		$filesize = filesize($filename);
		$data = array();
		while ($row = Helper_BSS_CSV::fgetcsvReg($handle, $filesize, ','))
		{
			$data[] = $row;
		}
		fclose($handle);
		$key = array_shift($data);
		$kdata = array();
		foreach ($data as $d)
		{
			$temp = array();
			foreach ($key as $k => $kv)
			{
				$temp[trim($kv)] = trim($d[$k]);
			}
			$kdata[] = $temp;
		}
		return $kdata;
	}
	
	static function importEabyOrderByCsv($filename)
	{
		$handle = fopen($filename,'r',false);
		$filesize = filesize($filename);
		$data = array();
		while ($row = fgetcsv($handle, $filesize, ','))
		{
			$data[] = $row;
		}
		fclose($handle);
		array_shift($data);
		$key = array_shift($data);
		array_shift($data);array_pop($data);array_pop($data);array_pop($data);
		$kdata = array();
		foreach ($data as $d)
		{
			$temp = array();
			foreach ($key as $k => $kv)
			{
				$temp[trim($kv)] = mb_convert_encoding(trim($d[$k]), 'UTF-8');
			}
			$kdata[] = $temp;
		}
		return $kdata;
	}
	
	static function importAmazonOrderByXlsx($filename)
	{
		require_once(Q::ini('custom_system/lib_dir') . 'PHPExcel.php');
		$PHPExcel = new PHPExcel();
		$PHPReader = new PHPExcel_Reader_Excel2007();
		$PHPExcel = $PHPReader->load($filename);
		$sheet = $PHPExcel->getActiveSheet();
		$height = $sheet->getHighestRow();
		$width = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
		$data = array();
		for($i=2; $i<=$height; $i++)
		{
			$row = array();
			for($j = 0; $j<$width; $j++)
			{
				$cell = $sheet->getCellByColumnAndRow($j,$i)->getValue();
				array_push($row,$cell);
			}
			array_push($data,$row);
		}
		return $data;
	}
	
	static function productInfoToCsv($product_info)
	{
		$data = "v_products_model,v_products_name_1,v_status,v_products_weight,v_products_price,v_date_added,v_products_quantity,v_products_description_1,v_HOST_NAME,v_categories_name_1,v_categories_name_2,v_categories_name_3\n";
		foreach ($product_info as $pi)
		{
			$cat_arr = OLM_Zencart_Categories::getAncestorIdById($pi['categories_id'], $pi['shop_id']);
			$data .= $pi['number'] . ',';
			$data .= $pi['title'] . ',';
			$data .= $pi['onsale_flag'] . ',';
			$data .= $pi['weight'] . ',';
			$data .= $pi['price'] . ',';
			$data .= $pi['create_time'] . ',';
			$data .= $pi['storage'] . ',';
			$data .= '"'.addslashes(($pi['description'])) . '",';
			$data .= $pi['md5'] . ',';
			if ($cat_arr[0])
			{
				$data .= $cat_arr[0] . ',';
			}
			else
			{
				$data .= ',';
			}
			if (isset($cat_arr[1]))
			{
				$data .= $cat_arr[1] . ',';
			}
			else
			{
				$data .= ',';
			}
			if (isset($cat_arr[2]))
			{
				$data .= $cat_arr[2] . ',';
			}
			else
			{
				$data .= ',';
			}
			$data .= "\n";
		}
		return $data;
	}
	
	static function pushProductInfoToCsv($product_info)
	{
		$data = "v_products_model,v_products_name_1,v_status,v_products_weight,v_products_price,v_date_added,v_products_quantity,v_products_description_1,v_HOST_NAME,v_categories_name_1,v_categories_name_2,v_categories_name_3\n";
		foreach ($product_info as $pi)
		{
			$cat_arr = OLM_Zencart_Categories::getAncestorIdById($pi['categories_id'], $pi['shop_id']);
			$data .= $pi['number'] . ',';
			$data .= $pi['title'] . ',';
			$data .= $pi['onsale_flag'] . ',';
			$data .= $pi['weight'] . ',';
			$data .= $pi['price'] . ',';
			$data .= $pi['create_time'] . ',';
			$data .= $pi['storage'] . ',';
			$data .= '"'.addslashes(htmlspecialchars($pi['description'])) . '",';
			$data .= $pi['md5'] . ',';
			if ($cat_arr[0])
			{
				$data .= $cat_arr[0] . ',';
			}
			else
			{
				$data .= ',';
			}
			if (isset($cat_arr[1]))
			{
				$data .= $cat_arr[1] . ',';
			}
			else
			{
				$data .= ',';
			}
			if (isset($cat_arr[2]))
			{
				$data .= $cat_arr[2] . ',';
			}
			else
			{
				$data .= ',';
			}
			$data .= "\n";
		}
		return base64_encode($data);
	}
	
	static function fgetcsvReg(&$handle, $length = null, $d = ',', $e = '"')
	{
		$d = preg_quote($d);
		$e = preg_quote($e);
		$_line = "";
		$eof=false;
		while ($eof != true)
		{
			$_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
			$itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
			if ($itemcnt % 2 == 0)
			$eof = true;
		}
		$_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
		$_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
		preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
		$_csv_data = $_csv_matches[1];
		for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++)
		{
			$_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
			$_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
		}
		return empty ($_line) ? false : $_csv_data;
	}
}